package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // Shop shop =  queryWithCacheThrough(id);//缓存穿透 存储null
        // Shop shop = queryWithCacheBreakdown(id);//缓存击穿 互斥锁

        // Shop shop = queryWithLogicalExpire(id);//缓存击穿   逻辑过期

        Shop shop =
                cacheClient.queryWithCachePenetration(
                        RedisConstants.CACHE_SHOP_KEY,
                        id,
                        Shop.class,
                        this::getById,
                        RedisConstants.CACHE_SHOP_TTL,
                        TimeUnit.MINUTES);
        // Shop shop = cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
        // this::getById, 20L, TimeUnit.MINUTES);

        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    //    /**
    //     * 缓存击穿 逻辑过期
    //     *
    //     * @param id
    //     * @return
    //     */
  /*
  private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
  private Shop queryWithLogicalExpire(Long id) {
      String shopkey = RedisConstants.CACHE_SHOP_KEY + id;

      String shopJson = stringRedisTemplate.opsForValue().get(shopkey);
      if (StrUtil.isBlank(shopJson)) {
          return null;
      }
      // 存在，判断过期时间
      // 未过期，返回
      // 过期，获取互斥锁，成功开启线程缓存重建返回，失败返回
      RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);

      Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
      LocalDateTime expireTime = redisData.getExpireTime();
      if (expireTime.isAfter(LocalDateTime.now())) {
          //未过期，返回
          return shop;
      }
      String lockKey = RedisConstants.LOCK_SHOP_KEY + id;

      boolean b = tryLock(lockKey);//获取锁成功也要doublecheck
      if (b) {
          CACHE_REBUILD_EXECUTOR.submit(() -> {
              //重建缓存
              try {
                  this.saveShop2Redis(id, 40L);
              } catch (Exception e) {
                  throw new RuntimeException(e);
              } finally {

                  this.unLock(lockKey);
              }
          });
      }
      return shop;
  }
  */
    //    public void saveShop2Redis(Long id, Long expireTime) {
    //        Shop byId = getById(id);
    //        try {
    //            Thread.sleep(200);
    //        } catch (InterruptedException e) {
    //            throw new RuntimeException(e);
    //        }
    //        RedisData redisData = new RedisData();
    //        redisData.setData(byId);
    //        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
    //        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,
    // JSONUtil.toJsonStr(redisData));
    //    }

    //    /**
    //     * 缓存击穿 互斥锁
    //     *
    //     * @param id
    //     * @return
    //     */
    //    private Shop queryWithCacheBreakdown(Long id) {
    //        String shopkey = RedisConstants.CACHE_SHOP_KEY + id;
    //        //1.查redis 存在返回
    //        //不存在查数据库，存在 存入redis 返回 不存在 返回错误
    //        String shopJson = stringRedisTemplate.opsForValue().get(shopkey);
    //        if (StrUtil.isNotBlank(shopJson)) {
    //            return JSONUtil.toBean(shopJson, Shop.class);
    //        }
    //        //缓存穿透 判断是否为空
    //        if (shopJson != null) {//此时不为null，是空串
    //            return null;
    //        }
    //        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
    //        //实现缓存重建：获取互斥锁，失败休眠重试，成功查询数据库，
    //        Shop shop = null;
    //        try {
    //            //击穿
    //            boolean isLock = tryLock(lockKey);//得到锁对象，每个店铺都有锁,设置成功为true
    //            if (!isLock) {
    //                //失败 返回
    //                Thread.sleep(50);
    //                return queryWithCacheBreakdown(id);
    //            }
    //            //此时获取锁成功，应该再次检查缓存是否存在，DoubleCheck，存在则无需重建缓存
    //            shopJson = stringRedisTemplate.opsForValue().get(shopkey);
    //            if (StrUtil.isNotBlank(shopJson)) {
    //                return JSONUtil.toBean(shopJson, Shop.class);
    //            }
    //            shop = getById(id);
    //            Thread.sleep(200);//模拟重建延迟
    //            if (shop == null) {
    //                //缓存穿透 将null写入redis
    //                stringRedisTemplate.opsForValue().set(shopkey, "",
    // RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
    //                return null;
    //            }
    //            stringRedisTemplate.opsForValue().set(shopkey, JSONUtil.toJsonStr(shop),
    // RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    //        } catch (InterruptedException e) {
    //            throw new RuntimeException(e);
    //        } finally {
    //            //击穿
    //            unLock(lockKey);
    //        }
    //        return shop;
    //    }

    //    /**
    //     * 缓存穿透
    //     *
    //     * @param id
    //     * @return
    //     */
  /*
      private Shop queryWithCachePenetration(Long id) {

      String shopkey = RedisConstants.CACHE_SHOP_KEY + id;
      //1.查redis
      // 存在返回
      // 不存在查数据库，存在 存入redis 返回 不存在 返回错误
      String shopJson = stringRedisTemplate.opsForValue().get(shopkey);
          if(StrUtil.isNotBlank(shopJson))

      {
          return JSONUtil.toBean(shopJson, Shop.class);
      }
      //缓存穿透 判断是否为空
          if(shopJson !=null)

      {//此时不为null，是空串，null执行数据库
          return null;
      }

      Shop shop = getById(id);
          if(shop ==null)

      {
          //缓存穿透 将null写入redis
          stringRedisTemplate.opsForValue().set(shopkey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
          return null;
      }
          stringRedisTemplate.opsForValue().

      set(shopkey, JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
          return shop;
  }
      */
    //    private boolean tryLock(String key) {
    //        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10,
    // TimeUnit.SECONDS);
    //        return BooleanUtil.isTrue(aBoolean);//预防空指针,空指针返回false
    //    }
    //
    //    private void unLock(String key) {
    //        Boolean delete = stringRedisTemplate.delete(key);
    //    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id为空");
        }
        updateById(shop);
        // 分布式中，可能是MQ通知对方删除缓存 分布式强一致性要用TTC
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1判断是否需要根据坐标查询
        if (x == null && y == null) {
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 2计算分页
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 3查redis，按距离排序,分页 结果shopId，distance   geosearch bylonlat x y byradius 10 withdistance
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results =
                stringRedisTemplate
                        .opsForGeo()
                        .search(
                                key,
                                GeoReference.fromCoordinate(x, y),
                                new Distance(5000),
                                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                                        .includeDistance()
                                        .limit(end));
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        // 4解析id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        if (content.size() <= from) {
            return Result.ok(Collections.emptyList());
        }
        ArrayList<Long> ids = new ArrayList<>(content.size());
        HashMap<String, Distance> hashMap = new HashMap<>();

        content.stream()
                .skip(from)
                .forEach(
                        r -> {
                            String shopIdStr = r.getContent().getName();
                            Distance distance = r.getDistance();
                            ids.add(Long.valueOf(shopIdStr));
                            hashMap.put(shopIdStr, distance);
                        });

        // 5根据id查shop
        String join = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id," + join + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(hashMap.get(shop.getId().toString()).getValue());
        }
        // 6根据类型分页查询
        return Result.ok(shops);
    }
}
